import { Popup, Step, Steps } from '@nutui/nutui-react-taro'
import '@nutui/nutui-react-taro/dist/style.css'
import { Image, ScrollView, Text, View } from '@tarojs/components'
import Taro, { useRouter } from '@tarojs/taro'
import React, { useMemo, useState } from 'react'
import { useRequest } from 'taro-hooks'
import Button from '../../components/button'
import Card from '../../components/card'
import Layout from '../../components/layout'
import SupervisorCard from '../../components/supervisor-card'
import { getOrderDetail } from '../../services/product'
import './index.less'

const OrderDetails: React.FC = () => {
  const router = useRouter()
  const { id } = router.params
  const [showContractModal, setShowContractModal] = useState(false)

  // 使用 taro-hooks 的 useRequest 获取订单详情
  const { data: orderDetailResponse, loading } = useRequest(getOrderDetail, {
    defaultParams: [{ orderNo: id }],
  })

  // 从响应中提取订单详情数据
  const orderDetail = useMemo(() => {
    return orderDetailResponse?.detail
  }, [orderDetailResponse])

  const handleCallSupervisor = (): void => {
    // 处理联系监督员逻辑
    Taro.makePhoneCall({
      phoneNumber: '138-XXXX-XXXX',
    }).catch((err) => {
      console.error('拨打电话失败:', err)
    })
  }

  const handleSignContract = (): void => {
    setShowContractModal(true)
  }

  const handleCloseContractModal = (): void => {
    setShowContractModal(false)
  }

  const handleContractSigned = (): void => {
    setShowContractModal(false)
    Taro.showToast({
      title: '合同签署成功',
      icon: 'success',
    })
  }

  // 订单状态步骤数据（写死，后续可从API获取）
  const orderSteps = [
    { title: '预约量房' },
    { title: '设计中' },
    { title: '待签约' },
    { title: '施工中' },
    { title: '待验收' },
    { title: '验收完成' },
    { title: '已结单' },
  ]

  // 当前步骤索引（从0开始，写死，后续可从API获取）
  const currentStep = 2 // 当前在"待签约"步骤

  // 检查当前状态是否为'待签约'
  const isWaitingForContract = currentStep === 2

  const handleProductClick = (productIndex: number): void => {
    const product = orderDetail?.products?.[productIndex]
    if (product) {
      console.log('跳转到产品详情:', product)
      // 后续可以根据实际需求跳转到产品详情页
      // Taro.navigateTo({
      //   url: `/pages/product-details/index?id=${product.id}`,
      // })
    }
  }

  // 如果数据还在加载或没有数据，显示加载状态
  if (!orderDetail && !loading) {
    return (
      <Layout title='订单详情' showTabBar={false}>
        <View className='order-details-container'>
          <Text>订单数据加载失败</Text>
        </View>
      </Layout>
    )
  }

  return (
    <Layout title='订单详情' showTabBar={false} loading={loading}>
      <ScrollView className='order-details-container' scrollY>
        {/* 订单基本信息 */}
        <Card className='order-basic-info'>
          <View className='order-info-row'>
            <Text className='order-info-label'>订单编号</Text>
            <Text className='order-info-value'>{orderDetail?.orderNo || '加载中...'}</Text>
          </View>
          <View className='order-info-row'>
            <Text className='order-info-label'>配送地址</Text>
            <Text className='order-info-value'>{orderDetail?.address?.address || '加载中...'}</Text>
          </View>
          <View className='order-info-row'>
            <Text className='order-info-label'>联系人</Text>
            <Text className='order-info-value'>
              {orderDetail?.address?.name || '加载中...'} {orderDetail?.address?.phone || ''}
            </Text>
          </View>
        </Card>

        {/* 现场监督信息（写死数据，后续可从API获取） */}
        <SupervisorCard
          name='张工'
          phone='138-XXXX-XXXX'
          avatar='https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=100&h=100&fit=crop&crop=face'
          onCall={handleCallSupervisor}
        />

        {/* 订单产品列表 */}
        <Card className='order-items-card'>
          <View className='order-items-header'>
            <Text className='order-items-title'>订单内容</Text>
          </View>
          <View className='order-items-list'>
            {orderDetail?.products?.map((product, index) => (
              <View key={index} className='order-product-item' onClick={() => handleProductClick(index)}>
                {/* 产品图片 */}
                <Image
                  className='product-image'
                  src={product.images?.[0] || ''}
                  mode='aspectFill'
                />

                {/* 产品信息 */}
                <View className='product-info'>
                  <Text className='product-name'>{product.name}</Text>
                  <Text className='product-description'>{product.description}</Text>

                  {/* 产品规格信息 */}
                  <View className='product-specs'>
                    <Text className='spec-item'>面积: {product.spaceSize}{product.spaceUnit || 'm²'}</Text>
                    <Text className='spec-item'>工期: {product.duration}</Text>
                  </View>

                  {/* 风格和色彩 */}
                  <View className='product-style'>
                    <Text className='style-item'>风格: {product.style?.name}</Text>
                    <Text className='style-item'>色彩: {product.colorScheme?.name}</Text>
                  </View>

                  {/* 产品金额 */}
                  <View className='product-amount'>
                    <Text className='amount-label'>金额</Text>
                    <Text className='amount-value'>¥{product.amount?.toLocaleString()}</Text>
                  </View>
                </View>

                {/* 箭头图标 */}
                <View className='product-arrow'>
                  <Text className='arrow-icon'>›</Text>
                </View>
              </View>
            ))}
          </View>

          {/* 订单总金额 */}
          <View className='order-total'>
            <Text className='total-label'>订单总额</Text>
            <Text className='total-amount'>¥{orderDetail?.totalPrice?.toLocaleString() || '0'}</Text>
          </View>
        </Card>

        {/* 订单状态 */}
        <Card className='order-status-card'>
          <View className='order-status-header'>
            <Text className='order-status-title'>订单状态</Text>
          </View>
          <View className='order-status-steps'>
            <Steps direction='vertical' value={currentStep}>
              {orderSteps.map((step, index) => (
                <Step key={index} value={index} title={step.title} />
              ))}
            </Steps>
          </View>
        </Card>

        {/* 底部签约按钮 */}
        {isWaitingForContract && (
          <View className='contract-footer'>
            <Button className='contract-button' onClick={handleSignContract}>
              立即签约
            </Button>
          </View>
        )}
      </ScrollView>

      {/* 合同签署弹框 */}
      <Popup
        visible={showContractModal}
        onClose={handleCloseContractModal}
        position='bottom'
        className='contract-modal'>
        <View className='contract-content'>
          <Text className='contract-description'>请您仔细阅读合同内容，确认无误后签署。</Text>

          <View className='contract-details'>
            <Text className='contract-section-title'>电子合同</Text>

            {/* 合同双方 */}
            <View className='contract-parties'>
              <Text className='contract-party'>甲方：{orderDetail?.address?.name || '客户'}</Text>
              <Text className='contract-party'>乙方：袋鼠焕新家</Text>
            </View>

            {/* 项目详情 */}
            <View className='project-details'>
              <Text className='project-detail'>工程地址：{orderDetail?.address?.address || '待确认'}</Text>
              <Text className='project-detail'>工程项目：{orderDetail?.products?.[0]?.name || '装修项目'}</Text>
              <Text className='project-detail'>工程总金额：¥{orderDetail?.totalPrice?.toLocaleString() || '0'}</Text>
              <Text className='project-detail'>工程工期：{orderDetail?.products?.[0]?.duration || '待确认'}</Text>
              <Text className='project-detail'>付款方式：分期付款</Text>
            </View>

            {/* 合同条款 */}
            <View className='contract-terms'>
              <Text className='terms-title'>合同条款：</Text>
              <Text className='term-text'>
                1. 设计与施工：乙方将根据甲方确认的设计方案进行施工。任何设计变更需双方书面确认。
              </Text>
              <Text className='term-text'>
                2. 材料供应：所有装修材料均由乙方提供，品牌和规格需符合合同附件中的规定。
              </Text>
              <Text className='term-text'>
                3. 工程验收：工程分为中期和末期两次验收。每次验收需双方代表在场，并在验收单上签字确认。
              </Text>
              <Text className='term-text'>
                4. 保修服务：工程竣工后，乙方提供为期两年的保修服务，覆盖所有非人为损坏的施工项目。
              </Text>
              <Text className='term-text'>5. 违约责任：任何一方未能履行合同义务，应承担相应的违约责任。</Text>
              <Text className='term-text'>
                6. 争议解决：合同履行过程中发生争议，双方应友好协商解决；协商不成的，可向项目所在地人民法院提起诉讼。
              </Text>
              <Text className='term-text'>7. 其他：本合同一式两份，甲乙双方各执一份，具有同等法律效力。</Text>
            </View>
          </View>
        </View>

        <View className='contract-actions'>
          <Button onClick={handleContractSigned} className='sign-button'>
            签署
          </Button>
        </View>
      </Popup>
    </Layout>
  )
}

export default OrderDetails
